$(function(){
    // 业务1：接收文章列表传入的参数并渲染到页面中
    let url = location.href
    let id =url.split("?")[1]
    // ajax搞起
    $.ajax({
        type:'get',
        url:'http://localhost:8080/api/v1'+'/admin/article/search',
        headers:{
            Authorization: localStorage.getItem('dsj_token')
        },
        data:{id},
        success:(res) =>{
            console.log(res);
            $('#inputTitle').val(res.data.title) //文章标题
            $('#category').val(res.data.author) //文章类别
            $('#articleDate').val(res.data.date) //发布时间
            $('#articleContent').val(res.data.content) //富文本
        }
    })
    // 文章类别渲染
    $.ajax({
        type:'get',
        url:'http://localhost:8080/api/v1'+'/index/category',
        headers:{
            Authorization: localStorage.getItem('dsj_token')
        },
        success:(res)=>{
            // console.log('文章类别',res);
            // 调用模板引擎
            const categoryLsit = template("classify-list",res)
            $('#category').html(categoryLsit)
        }
    })
    // 日期插件
    function resDate(){
        layui.use('laydate', function(){
            var laydate = layui.laydate;
            //执行一个laydate实例
            laydate.render({
              elem: '#articleDate' //指定元素
            });
          });
    }
    // 富文本编辑器
    function richText(){
        tinymce.init({
            selector: '#mytextarea',
            language:'zh_CN'
          });
    }
    richText()
    resDate()
    // 业务2：编辑文章
    $('.btn-edit').on('click',function(e){
        e.preventDefault()
        // 拿到表单的value值
        let inputTitle = $('#inputTitle').val()
        let cover = $('#inputCover').val()
        let category =  $('#category').val()
        let compileDate = $('#articleDate').val()
        let largeText =  $('#mytextarea').val()
        console.log(largeText);
        console.log(inputTitle,category,compileDate,largeText);
        // ajax发请求搞起
        $.ajax({
            type:'post',
            url:'http://localhost:8080/api/v1'+'/admin/article/edit',
            headers:{
                Authorization: localStorage.getItem('dsj_token')
            },
            data:{
                id,
                title:inputTitle, //标题
                cover,            //封面
                categoryId:category, //分类
                date:compileDate, //时间
                content:largeText,  //内容
                state:'已发布'
            },
            success:(res)=>{
                if(res.msg === '修改成功'){
                    alert(res.msg)
                    location.href='article_list.html'
                }else{
                    alert(res.msg)
                }
            }
        })
    })
})